package com.weixue.controller.admin;

import com.weixue.common.Constants;
import com.weixue.common.NongFuMallCategoryLevelEnum;
import com.weixue.common.ServiceResultEnum;
import com.weixue.entity.GoodsCategory;
import com.weixue.entity.NongFuMallGoods;
import com.weixue.service.NongFuMallCategoryService;
import com.weixue.service.NongFuMallGoodsService;
import com.weixue.utils.PageQueryUtil;
import com.weixue.utils.Result;
import com.weixue.utils.ResultGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Day28
 *      商品管理模块--商品编辑
 */
@Controller
@RequestMapping("/admin")
public class NongFuMallGoodsController {

    @Resource
    private NongFuMallGoodsService nongFuMallGoodsService;
    @Resource
    private NongFuMallCategoryService nongFuMallCategoryService;



    /**
     * Day28
     *      页面跳转/admin/nongfu_mall_goods_edit.html
     *          1.商品信息添加页面需要进行分类选择，所以需要把分类的三级联动初始化数据也查询并设置到request域中。
     *          2.三级分类联动的知识点
     *      Collections.singletonList(0L)设置List中只能存放一个元素，多一个或者少一个都会导致异常。
     *      NongFuMallCategoryLevelEnum.LEVEL_ONE.getLevel()获取枚举类设置的常量对象，有level和name
     */
    @GetMapping("/goods/edit")
    public String edit(HttpServletRequest request) {
        request.setAttribute("path", "edit");
        //查询所有的一级分类
        List<GoodsCategory> firstLevelCategories = nongFuMallCategoryService.selectByLevelAndParentIdsAndNumber
                (Collections.singletonList(0L), NongFuMallCategoryLevelEnum.LEVEL_ONE.getLevel());
        if (!CollectionUtils.isEmpty(firstLevelCategories)) {
            //查询一级分类列表中第一个实体的所有二级分类
            List<GoodsCategory> secondLevelCategories = nongFuMallCategoryService.selectByLevelAndParentIdsAndNumber
                    (Collections.singletonList(firstLevelCategories.get(0).getCategoryId()), NongFuMallCategoryLevelEnum.LEVEL_TWO.getLevel());
            if (!CollectionUtils.isEmpty(secondLevelCategories)) {
                //查询二级分类列表中第一个实体的所有三级分类
                List<GoodsCategory> thirdLevelCategories = nongFuMallCategoryService.selectByLevelAndParentIdsAndNumber
                        (Collections.singletonList(secondLevelCategories.get(0).getCategoryId()), NongFuMallCategoryLevelEnum.LEVEL_THREE.getLevel());
                request.setAttribute("firstLevelCategories", firstLevelCategories);
                request.setAttribute("secondLevelCategories", secondLevelCategories);
                request.setAttribute("thirdLevelCategories", thirdLevelCategories);
                request.setAttribute("path", "goods-edit");
                return "/admin/nongfu_mall_goods_edit";
            }
        }
        return "error/error_5xx";
    }

    /**
     * Day30
     *      页面跳转到/admin/nongfu_mall_goods_edit.html页面
     *      查询商品信息编辑页所需的商品信息详情内容。
     *      该方法中有一段代码是关于分类数据列表的查询。
     *
     *      查询分类数据分为两种情况
     *          1.是商品表中关联的分类id为0，表示分类数据并未关联，就需要把分类数据按照在添加时的情况处理。
     *          2.是商品表中关联的id为正常三级分类的id。在这种情况下，需要在进入编辑页时将该三级分类和该三级分类关联的二级分类和一级分类设置为选中状态。
     *
     *      因此，这里做了如上代码的处理。首先查询当前三级分类C，紧接着查询该三级分类的上级分类B，然后根据B的主键查询出与C分类同级的三级分类列表。
     *      同理，再查出与B分类同级的二级分类列表和一级分类列表。
     *      当然，这里还要查出B分类的父级分类A。这样在初始化时的分类列表数据就都得到了，需要选中的一级分类A、二级分类B、三级分类C三个分类数据也都查询到。
     *      最后，将对应的数据放入request域中并转发到goods_edit.html模板页面中。
     */
    @GetMapping("/goods/edit/{goodsId}")
    public String edit(HttpServletRequest request, @PathVariable("goodsId") Long goodsId) {
        request.setAttribute("path", "edit");
        NongFuMallGoods nongFuMallGoods = nongFuMallGoodsService.getNongFuMallGoodsById(goodsId);
        if (nongFuMallGoods == null) {
            return "error/error_400";
        }
        if (nongFuMallGoods.getGoodsCategoryId() > 0) {
            if (nongFuMallGoods.getGoodsCategoryId() != null || nongFuMallGoods.getGoodsCategoryId() > 0) {
                //有分类字段则查询相关分类数据返回给前端以供分类的三级联动显示
                GoodsCategory currentGoodsCategory = nongFuMallCategoryService.getGoodsCategoryById
                        (nongFuMallGoods.getGoodsCategoryId());
                //商品表中存储的分类id字段为三级分类的id，不为三级分类则是错误数据
                if (currentGoodsCategory != null && currentGoodsCategory.getCategoryLevel() == NongFuMallCategoryLevelEnum.LEVEL_THREE.getLevel()) {
                    //查询所有的一级分类
                    List<GoodsCategory> firstLevelCategories = nongFuMallCategoryService.selectByLevelAndParentIdsAndNumber
                            (Collections.singletonList(0L), NongFuMallCategoryLevelEnum.LEVEL_ONE.getLevel());
                    //根据parentId查询当前parentId下所有的三级分类
                    List<GoodsCategory> thirdLevelCategories = nongFuMallCategoryService.selectByLevelAndParentIdsAndNumber
                            (Collections.singletonList(currentGoodsCategory.getParentId()), NongFuMallCategoryLevelEnum.LEVEL_THREE.getLevel());
                    //查询当前三级分类的父级二级分类
                    GoodsCategory secondCategory = nongFuMallCategoryService.getGoodsCategoryById(currentGoodsCategory.getParentId());
                    if (secondCategory != null) {
                        //根据parentId查询当前parentId下所有的二级分类
                        List<GoodsCategory> secondLevelCategories = nongFuMallCategoryService.selectByLevelAndParentIdsAndNumber
                                (Collections.singletonList(secondCategory.getParentId()), NongFuMallCategoryLevelEnum.LEVEL_TWO.getLevel());
                        //查询当前二级分类的父级一级分类
                        GoodsCategory firestCategory = nongFuMallCategoryService.getGoodsCategoryById(secondCategory.getParentId());
                        if (firestCategory != null) {
                            //所有分类数据都得到之后放到request对象中供前端读取
                            request.setAttribute("firstLevelCategories", firstLevelCategories);
                            request.setAttribute("secondLevelCategories", secondLevelCategories);
                            request.setAttribute("thirdLevelCategories", thirdLevelCategories);
                            request.setAttribute("firstLevelCategoryId", firestCategory.getCategoryId());
                            request.setAttribute("secondLevelCategoryId", secondCategory.getCategoryId());
                            request.setAttribute("thirdLevelCategoryId", currentGoodsCategory.getCategoryId());
                        }
                    }
                }
            }
        }
        if (nongFuMallGoods.getGoodsCategoryId() == 0) {
            //查询所有的一级分类
            List<GoodsCategory> firstLevelCategories = nongFuMallCategoryService.selectByLevelAndParentIdsAndNumber
                    (Collections.singletonList(0L), NongFuMallCategoryLevelEnum.LEVEL_ONE.getLevel());
            if (!CollectionUtils.isEmpty(firstLevelCategories)) {
                //查询一级分类列表中第一个实体的所有二级分类
                List<GoodsCategory> secondLevelCategories = nongFuMallCategoryService.selectByLevelAndParentIdsAndNumber
                        (Collections.singletonList(firstLevelCategories.get(0).getCategoryId()), NongFuMallCategoryLevelEnum.LEVEL_TWO.getLevel());
                if (!CollectionUtils.isEmpty(secondLevelCategories)) {
                    //查询二级分类列表中第一个实体的所有三级分类
                    List<GoodsCategory> thirdLevelCategories = nongFuMallCategoryService.selectByLevelAndParentIdsAndNumber
                            (Collections.singletonList(secondLevelCategories.get(0).getCategoryId()), NongFuMallCategoryLevelEnum.LEVEL_THREE.getLevel());
                    request.setAttribute("firstLevelCategories", firstLevelCategories);
                    request.setAttribute("secondLevelCategories", secondLevelCategories);
                    request.setAttribute("thirdLevelCategories", thirdLevelCategories);
                }
            }
        }
        request.setAttribute("goods", nongFuMallGoods);
        request.setAttribute("path", "goods-edit");
        return "/admin/nongfu_mall_goods_edit";
    }


    /**
     * Day29
     *      添加接口
     */
    @RequestMapping(value = "/goods/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(@RequestBody NongFuMallGoods nongFuMallGoods) {
        if (StringUtils.isEmpty(nongFuMallGoods.getGoodsName())
                || StringUtils.isEmpty(nongFuMallGoods.getGoodsIntro())
                || StringUtils.isEmpty(nongFuMallGoods.getTag())
                || Objects.isNull(nongFuMallGoods.getOriginalPrice())
                || Objects.isNull(nongFuMallGoods.getGoodsCategoryId())
                || Objects.isNull(nongFuMallGoods.getSellingPrice())
                || Objects.isNull(nongFuMallGoods.getStockNum())
                || Objects.isNull(nongFuMallGoods.getGoodsSellStatus())
                || StringUtils.isEmpty(nongFuMallGoods.getGoodsCoverImg())
                || StringUtils.isEmpty(nongFuMallGoods.getGoodsDetailContent())) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        String result = nongFuMallGoodsService.saveNongFuMallGoods(nongFuMallGoods);
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }


    /**
     * Day30
     *      修改接口
     */
    @RequestMapping(value = "/goods/update", method = RequestMethod.POST)
    @ResponseBody
    public Result update(@RequestBody NongFuMallGoods nongFuMallGoods) {
        if (Objects.isNull(nongFuMallGoods.getGoodsId())
                || StringUtils.isEmpty(nongFuMallGoods.getGoodsName())
                || StringUtils.isEmpty(nongFuMallGoods.getGoodsIntro())
                || StringUtils.isEmpty(nongFuMallGoods.getTag())
                || Objects.isNull(nongFuMallGoods.getOriginalPrice())
                || Objects.isNull(nongFuMallGoods.getSellingPrice())
                || Objects.isNull(nongFuMallGoods.getGoodsCategoryId())
                || Objects.isNull(nongFuMallGoods.getStockNum())
                || Objects.isNull(nongFuMallGoods.getGoodsSellStatus())
                || StringUtils.isEmpty(nongFuMallGoods.getGoodsCoverImg())
                || StringUtils.isEmpty(nongFuMallGoods.getGoodsDetailContent())) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        String result = nongFuMallGoodsService.updateNongFuMallGoods(nongFuMallGoods);
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }

    /**
     * Day30
     *      页面跳转/admin/nongfu_mall_goods.html
     */
    @GetMapping("/goods")
    public String goodsPage(HttpServletRequest request) {
        request.setAttribute("path", "nongfu_mall_goods");
        return "/admin/nongfu_mall_goods";
    }

    /**
     * Day30
     *      分页列表
     */
    @RequestMapping(value = "/goods/list", method = RequestMethod.GET)
    @ResponseBody
    public Result list(@RequestParam Map<String, Object> params) {
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(nongFuMallGoodsService.getNongFuMallGoodsPage(pageUtil));
    }

    /**
     * Day30
     *      批量修改销售状态
     */
    @RequestMapping(value = "/goods/status/{sellStatus}", method = RequestMethod.PUT)
    @ResponseBody
    public Result delete(@RequestBody Long[] ids, @PathVariable("sellStatus") int sellStatus) {
        if (ids.length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        if (sellStatus != Constants.SELL_STATUS_UP && sellStatus != Constants.SELL_STATUS_DOWN) {
            return ResultGenerator.genFailResult("状态异常！");
        }
        if (nongFuMallGoodsService.batchUpdateSellStatus(ids, sellStatus)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("修改失败");
        }
    }


    /**
     * 详情
     */
    @GetMapping("/goods/info/{id}")
    @ResponseBody
    public Result info(@PathVariable("id") Long id) {
        NongFuMallGoods goods = nongFuMallGoodsService.getNongFuMallGoodsById(id);
        if (goods == null) {
            return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        return ResultGenerator.genSuccessResult(goods);
    }


}